<template>
  <el-upload
      class="avatar-uploader"
      action="/api/file/upload"
      :show-file-list="false"
      :on-success="(response, file, fileList) => {handleAvatarSuccess(response,file,fileList)}">
    <img v-if="form" :src="form" class="w-100 h-100" style="object-fit: fill" alt="">
    <i v-else class="w-100 el-icon-plus"></i>
    <!--    <div slot="tip" class="el-upload__tip">请上传图片，且不超过5MB</div>-->
  </el-upload>
</template>
<script>
import {FileApi} from "@/api/api";

export default {
  name: "WrdImgUpload",
  props: {
    url: {
      type: String
    }
  },
  data() {
    return {
      FileApi,
      form: this.url
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code !== 1) {
        this.$message.error(res.data)
        return
      }
      this.$message.success("上传成功");
      this.form=res.data;
      this.hook()
    },
    beforeImgUpload(file) {
      const IMG_TYPE = [
        'image/jpeg',
        'image/jpg',
        'image/png'];
      const isImage = IMG_TYPE.includes(file.type);
      if (!isImage) {
        this.$message.error('上传图片格式不正确!');
        return false;
      }
      const isLtSize = file.size / 1024 / 1024 < 5;
      if (!isLtSize) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      return true;
    },
    hook() {
      this.$emit('onSuccess', this.form);
      this.form = null;
    }
  }
}
</script>
<style scoped>
/deep/ el-upload {
  width: 100%;
}
</style>
